package com.smforj.ssm.modules.wc.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.smforj.ssm.frame.core.constant.Separator;
import com.smforj.ssm.frame.core.utils.StringEx;
import com.smforj.ssm.frame.core.web.domain.DataResult;
import com.smforj.ssm.frame.core.web.domain.DataResult.DataStatus;
import com.smforj.ssm.modules.lib.service.LibraryService;
import com.smforj.ssm.modules.lib.service.ReaderWechatService;
import com.smforj.ssm.modules.sys.util.SIP2MsgGdlis;
import com.smforj.ssm.modules.lib.constant.TerminalType;
import com.smforj.ssm.modules.lib.domain.CheckOutResponse;
import com.smforj.ssm.modules.lib.domain.LibraryRequest;
import com.smforj.ssm.modules.lib.domain.LoginUser;
import com.smforj.ssm.modules.lib.domain.SysBook;
import com.smforj.ssm.modules.lib.domain.SysReader;
import com.smforj.ssm.modules.lib.domain.SysReaderWechat;
import com.smforj.ssm.modules.lib.domain.Terminal;
import com.smforj.ssm.modules.lib.domain.query.SysBookQuery;
import com.smforj.ssm.modules.lib.domain.vo.SysBookVo;
import com.smforj.ssm.modules.lib.service.BookInfoService;
import com.smforj.ssm.wechat.enums.EnumMessage;
import com.smforj.ssm.wechat.service.CoreServiceImpl;
import com.smforj.ssm.wechat.util.MessageUtil;

/***
 * 微信Service 该对象不抛异常
 *
 * @author Haijun Gao 
 * @date 2016-8-6 下午4:02:55
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */
@Service
public class WechatService extends CoreServiceImpl {

    private Logger log = Logger.getLogger(this.getClass());
    @Autowired 
    @Qualifier("esbusinessService")
    private BusinessService businessService;
    @Autowired
    private LibraryService libraryService;
    @Autowired
    @Qualifier("sysBookInfoService")
    private BookInfoService bookInfoService;

    @Autowired
    private ReaderWechatService readerWechatService;

    /***
     * TAG信息
     */
    private static final String REGISTERTAG = " \r\n* 注册:\r\ncm00|AA借阅证号|ay\r\n";
    private static final String CHECKOUTTAG = " \r\n* 借阅：\r\ncm11|AB图书id（条码）|AD证件密码（非必须）|ay\r\n";
    private static final String RENEWTAG = " \r\n* 续借:\r\ncm29|AB图书id（条码）|AD证件密码（非必须）|ay\r\n";
    private static final String VIEWTAG = " \r\n* 查询借阅情况:\r\ncm01|AD证件密码（非必须）|ay\r\n";
    private static final String QUERYTAG = " \r\n* 查询图书信息:\r\ncm02|AJ图书名称|ay\r\n";

    /**
     * 根据文本消息判断是否是执行业务操作命令
     * 1、借书
     * 2、续借
     * 3、查询
     * <p>
     * 命令组成
     * cm + 业务指令 + | + param
     * <p>
     * 借：cm11|AB图书id（条码）|AD证件密码（非必须）|ay
     * 续借:cm29|AB图书id（条码）|AD证件密码（非必须）|ay
     * 查询:cm00|AD证件密码（非必须）|ay
     */
    @Override
    @Transactional
    public String doText() {
        String iRes = "";
        //消息内容
        String content = getRequestMap().get(EnumMessage.CONTENT);
        String appid = getRequestMap().get(EnumMessage.FROMUSERNAME);
        if (StringEx.isExEmpty(content))
            return iRes;
        //去除两边空格
        content = content.trim();
        if (!checkCommand(content))
            return iRes = String.format("%s%s%s%s%s", REGISTERTAG,
                    CHECKOUTTAG, RENEWTAG, VIEWTAG, QUERYTAG);

        String command = content.substring(2, 4);
        if (command.equals("00"))//注册
        {
            log.info(String.format("doText content: %s", content));
            iRes = excuteSignIn(content, appid);
        } else if (command.equals("02")) {//查询图书
            log.info(String.format("doText content: %s", content));
            iRes = excuteQuery(content);
        } else {
            //获取读者信息
            SysReaderWechat rw = readerWechatService.getReaderWechat(appid);
            if (rw == null || rw.getReader() == null || StringEx.isExEmpty(rw.getAppid()))
                return iRes = String.format("您未注册%s", REGISTERTAG);
            log.info(String.format("doText content: %s appid: %s", content, appid));
            if (command.equals("11")) //借阅
            {
                iRes = excuteCheckOut(content, appid, rw.getReader());
            } else if (command.equals("29")) //续借
            {
                iRes = excuteRevew(content, appid, rw.getReader());
            } else if (command.equals("01")) //查询借阅信息
            {
                iRes = excuteView(appid, rw.getReader());
            } else {
                iRes = "指令不正确\r\n" + String.format("%s%s%s%s%s", REGISTERTAG,
                        CHECKOUTTAG, RENEWTAG, VIEWTAG, QUERYTAG);
            }
        }
        return iRes;
    }

    /***
     * 执行查询
     * @param appid
     * @param reader
     * @return
     * @date 2016-8-30 下午5:40:57
     */
    private String excuteView(String appid, SysReader reader) {
        Terminal terminal = getTerminal(appid);
        LoginUser user = new LoginUser();
        //金至执行借
        user.setReader(reader);
        System.out.println("excuteView reader: " + reader.getReaderName());
        //terminal.setRemark(String.format("微信用户{0}执行查询操作",appid));
        DataResult result = businessService.doQuery(terminal, user);
        if (result.getStatus() == DataStatus.OK)
            return String.format("查询成功 {0}", user.getReader().getReaderName());
        else
            return String.format("查询失败 {0}", user.getReader().getReaderName());
    }

    /***
     * 执行续借
     * @param content
     * @param appid
     * @param reader
     * @return
     * @date 2016-8-30 下午5:34:09
     */
    private String excuteRevew(String content, String appid, SysReader reader) {
        String[] stra = content.split(Separator.SVERTICAL);
        //证件密码
        String szUserPWD = SIP2MsgGdlis.getContentByField(stra, "AD");
        String barcode = SIP2MsgGdlis.getContentByField(stra, "AB");
        Terminal terminal = getTerminal(appid);
        LoginUser user = new LoginUser();
        //金至执行借
        user.setReader(reader);
        SysBookVo book = new SysBookVo();
        book.setBarcode(barcode);
        System.out.println("excuteRevew barcode: " + barcode);
        book = (SysBookVo) businessService.getBookInfo(book);
        if (book != null) {
            //terminal.setRemark(String.format("微信用户{0}执行续借操作",appid));

            //图书管理软件执行
            CheckOutResponse response = libraryService.doRenew(getRequest(reader, barcode, szUserPWD)).get(0);

            //设置信息
            //book.setOccurDate(DateUtils.parseDate(response.getOccurDate(), "yyyy-MM-dd"));
            //book.setNeedReturnDate(DateUtils.parseDate(response.getNeedReturnDate()));
            DataResult result = businessService.doRenewBook(book, terminal, user);

            if (result.getStatus() == DataStatus.OK)
                return String.format("续借成功 {0}", book.getBookname());
            else
                return String.format("续借失败 {0}", book.getBookname());

        } else
            return String.format("找不到图书信息{0}", barcode);
    }

    /***
     * 执行借阅
     * @param content
     * @param appid
     * @param reader
     * @return
     * @date 2016-8-30 下午5:34:09
     */
    private String excuteCheckOut(String content, String appid, SysReader reader) {
        String[] stra = content.split(Separator.SVERTICAL);
        //证件密码
        String szUserPWD = SIP2MsgGdlis.getContentByField(stra, "AD");
        Terminal terminal = getTerminal(appid);
        LoginUser user = new LoginUser();
        //金至执行借
        user.setReader(reader);
        String barcode = SIP2MsgGdlis.getContentByField(stra, "AB");
        SysBookVo book = new SysBookVo();
        book.setBarcode(barcode);
        System.out.println("excuteCheckOut barcode: " + barcode);
        book = (SysBookVo) businessService.getBookInfo(book);
        if (book != null) {
            //terminal.setRemark(String.format("微信用户{0}执行借书操作",appid));

            //图书管理软件执行
            CheckOutResponse response = libraryService.doCheckout(getRequest(reader, barcode, szUserPWD)).get(0);

            //设置信息
            //book.setOccurDate(response.getOccurDate());
            //book.setNeedReturnDate(response.getNeedReturnDate());
            DataResult result = businessService.doBorrowBook(book, terminal, user);

            if (result.getStatus() == DataStatus.OK)
                return String.format("借阅成功 {0}", book.getBookname());
            else
                return String.format("借阅失败 {0}", book.getBookname());
        } else
            return String.format("找不到图书信息{0}", barcode);
    }

    /***
     * 执行查询图书信息
     * @param content cm02|AJ图书名称|ay
     * @return
     * @date 2016-8-30 下午5:20:39
     */
    private String excuteQuery(String content) {
        String[] stra = content.split(Separator.SVERTICAL);
        //图书名称
        String bookname = SIP2MsgGdlis.getContentByField(stra, "AJ");
        System.out.println("excuteQuery bookname: " + bookname);
        SysBookQuery query = new SysBookQuery();
        query.setBookname(bookname);
        List<SysBook> list = bookInfoService.queryList(query);
        StringBuilder sb = new StringBuilder();
        if (list != null) {
            for (SysBook book : list)
                sb.append(String.format("图书名称：%s \r\n条码：%s \r\n\r\n\r\n\r\n", book.getBookname(), book.getBarcode()));
        }
        return sb.toString();
    }

    /***
     * 执行注册功能
     * @param content
     * @param appid
     * @return
     * @date 2016-8-30 下午5:19:04
     */
    private String excuteSignIn(String content, String appid) {
        String[] stra = content.split(Separator.SVERTICAL);
        //证件号
        String campusCardNum = SIP2MsgGdlis.getContentByField(stra, "AA");
        System.out.println("excuteSignIn campusCardNum: " + campusCardNum);
        SysReader reader = new SysReader();
        reader.setCampusCardNum(campusCardNum);
        DataResult result = businessService.addWechatUser(reader, appid);
        return result.getMessage() == null ? "" : result.getMessage().toString();
    }

    /***
     * 检测是否是错误指令
     * @param content
     * @return
     * @date 2016-8-30 下午5:06:37
     */
    private Boolean checkCommand(String content) {
        if (content.length() >= 6 && content.toLowerCase().startsWith("cm") && content.toLowerCase().endsWith("ay")) {
            String command = content.toLowerCase().substring(2, 4);
            switch (command) {
                case "00":
                case "01":
                case "02":
                case "11":
                case "29":
                    return true;
            }
        }
        return false;
    }

    /***
     * 获取Terminal
     * @param appid
     * @return
     * @date 2016-8-30 下午4:20:24
     */
    private Terminal getTerminal(String appid) {
        Terminal terminal = new Terminal();
        terminal.setId(appid);
        terminal.setTerminalType(TerminalType.WECHAT);
        return terminal;
    }

    private LibraryRequest getRequest(SysReader rw, String bookid, String szUserPWD) {
        LibraryRequest request = new LibraryRequest();
        SysBook book = new SysBook();
        book.setBarcode(bookid);
        //request.getBookList().set(0, book);
        request.setSzUserId(rw.getCampusCardNum());
        request.setSzUserPWD(szUserPWD);
        return request;
    }

    @Override
    public String doImage() {
        return "正在建设中。。。";
    }

    @Override
    public String doLocation() {
        return "正在建设中。。。";
    }

    @Override
    public String doLink() {
        return "正在建设中。。。";
    }

    /***
     * 只处理click事件，对于消息点击事件不进行处理
     */
    @Override
    public String doEvent() {
        System.out.println("doevent");
        String iRes = "";
        // 事件类型
        String eventType = getRequestMap().get("Event");
        //  注册
        if (eventType.equalsIgnoreCase(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
            System.out.println("EVENT_TYPE_SUBSCRIBE  " + eventType);
            iRes = "SUBSCRIBE";
        } else if (eventType.equalsIgnoreCase(MessageUtil.EVENT_TYPE_CLICK)) {// 自定义菜单点击事件
            // 事件KEY值，与创建自定义菜单时指定的KEY值对应
            System.out.println("EVENT_TYPE_CLICK  " + eventType);
            iRes = "";
        } else if (eventType.equalsIgnoreCase(MessageUtil.EVENT_TYPE_VIEW)) {
            iRes = "";
            System.out.println("EVENT_TYPE_VIEW  " + eventType);
        } else if (eventType.equalsIgnoreCase(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
            iRes = "您走了，我会想您的亲！！！";
        } else {
            System.out.println("other  " + eventType);
            iRes = "欢迎来到金至集团云图书馆" + String.format("\r\n%s%s%s%s%s", REGISTERTAG,
                    CHECKOUTTAG, RENEWTAG, VIEWTAG, QUERYTAG);
        }
        return iRes;
    }

    @Override
    public String doVoice() {
        return "正在建设中。。。";
    }

    /**
     * 目前不用权限判断
     */
    @Override
    public Boolean checkPrem() {
        return true;
    }

}
